<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;

/**
 * App\Models\UserCard
 *
 * @property int $id
 * @property int $user_card_id 用户会员卡ID
 * @property int $user_id 用户ID
 * @property int $car_id 车辆ID
 * @property int $card_id 会员卡ID
 * @property string $service_id 服务ID
 * @property string $service_name 服务名称
 * @property int $number 洗车次数
 * @property int $old_number 原洗车次数
 * @property int $range 使用限制:0=全场通用,1=指定服务
 * @property string $start_time 开启日期
 * @property string $end_time 结束日期
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read \App\Models\User|null $user
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard query()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereCarId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereCardId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereEndTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereStartTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereUserId($value)
 * @mixin \Eloquent
 */
class UcService extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'uc_service';

    protected $fillable = [
        "user_card_id","user_id","service_id","service_name","range","car_num","shop_id",
        "car_id","number","price","start_time","end_time","old_number","card_id","discount"
    ];

    protected $casts = ['price'=>'float'];

    protected $appends = ['text'];

    public function getTextAttribute():string
    {
        $range = $this->attributes['range'];
        $shop_id = $this->attributes['shop_id'];
        $service_id = $this->attributes['service_id'];
        if ($range==1){
            $shop = ShopUser::query()->where("id",$shop_id)->first();
            if ($shop){
                $text = "限定【{$shop->name}】门店使用";
            }else{
                $text = "使用已失效";
            }
        }elseif ($range==2){
            $service = Service::find($service_id);
            if ($service){
                $text = "限定【{$service->title}】服务使用";
            }else{
                $text = "使用已失效";
            }
        }else{
            $text = "全场通用";
        }
        return $text;
    }

    /**
     * 添加洗车卡
     * @param $order_id
     * @param $user_id
     * @param $extend
     * @return UserCard|Model
     */
    public static function addCard($order_id,$user_id,$extend)
    {
        $card = $extend['card'];
        $car = $extend['car'];
        unset($car['created_at']);
        unset($car['updated_at']);
        unset($car['is_default']);
        $params = [
            'user_id'=>$user_id,"card_id"=>$card['id'],'title'=>$card['title'],'range'=>$card['range'],
            'price'=>$card['price'],'cid'=>$card['cid'],'service_id'=>$card['service_id'],'shop_id'=>$card['shop_id'],
            'car_id'=>$car['id'],'areas'=>$card['areas'],"car"=>$car,"order_id"=>$order_id,
            "number"=>$card['number'],"old_number"=>$card['number']
        ];
        $days = $card['days'];
        $start_time = now()->format("Y-m-d");
        $end_time = now()->addDays($days)->format("Y-m-d");
        $params['start_time'] = $start_time;
        $params['end_time'] = $end_time;
        return self::create($params);
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class,"id","user_id");
    }

    public function order(): HasOne
    {
        return $this->hasOne(PaymentOrder::class,"id","order_id");
    }

    /**
     * 获取洗车卡列表
     * @param $user_id
     * @return array
     */
    public static function getList($user_id): array
    {
        $pageSize = request()->input("pageSize",10);
        $type = request()->input("type",0);
        $where = ['user_id'=>$user_id];
        $model = self::query()->where($where);
        if ($type){
            $where1 = function ($query){
                $query->whereDate("start_time",">",now())
                    ->whereDate("end_time","<",now());
            };
            $where2 = function ($query){
                $query->where("number",0);
            };
            $query = $model->where($where1)->orWhere($where2);
        }else{
            $query = $model->where("number",">",0)->whereDate("start_time","<=",now())
                ->whereDate("end_time",">=",now());
        }
        $list = $query->orderByDesc("id")->paginate($pageSize);
        $data['items'] = $list->items();
        $data['lastPage'] = $list->lastPage();
        $data['total'] = $list->total();
        return $data;
    }

    /**
     * @param $user_id
     * @return array
     */
    public static function allows($user_id): array
    {
        $longitude = request()->input("longitude","");
        $latitude = request()->input("latitude","");
        $service_id = request()->input("service_id","");
        $car_id = request()->input("car_id","");
        $service = Service::find($service_id);
        if (!$service){
            modelError("找不到此服务!");
        }
        $shop_id = $service->shop_id;
        $area_id = 0;
        if ($longitude&&$latitude){
            $area_id = Area::findAddress($longitude,$latitude);
        }
        $map1 = ["range"=>0,'user_id'=>$user_id,"car_id"=>$car_id,"shop_id"=>0];
        $map2 = ["range"=>1,'user_id'=>$user_id,"car_id"=>$car_id,"shop_id"=>$shop_id];
        $map3 = ["range"=>2,'user_id'=>$user_id,"service_id"=>$service_id,"car_id"=>$car_id];
        $where1 = function ($query) use ($map1,$area_id) {
            $query->where($map1)->where("number",">",0)->whereNull("areas");
        };
        $where2 = function ($query) use ($map2,$area_id) {
            $query->where($map2)->where("number",">",0)->whereNull("areas");
        };
        $where3 = function ($query) use ($map3,$area_id) {
            $query->where($map3)->where("number",">",0)->whereNull("areas");
        };
        $where4 = function ($query) use ($where1,$area_id) {
            $query->where($where1)->when($area_id,function ($query,$value){
                $query->findInSet("areas",$value);
            });
        };
        $where5 = function ($query) use ($where2,$area_id) {
            $query->where($where2)->when($area_id,function ($query,$value){
                $query->findInSet("areas",$value);
            });
        };
        $where6 = function ($query) use ($where3,$area_id) {
            $query->where($where3)->when($area_id,function ($query,$value){
                $query->findInSet("areas",$value);
            });
        };
        $list = self::query()->where($where1)
            ->orWhere($where2)
            ->orWhere($where3)
            ->orWhere($where4)
            ->orWhere($where5)
            ->orWhere($where6)
            ->get();
        return $list->toArray();
    }

}
